import {
	symbol
} from "../../common/config.js"
import {
	guid
} from "../../utils/common.js"
import {
	addGraphicLayer
} from "../../utils/graphic.js"

/**
 * 地图绘制
 * @param type				绘制类型： point点，polyline线，multipoint多面，polygon面，rectangle，circle圆
 * @param view				视图对象
 * @param pointSymbol		点symbol
 * @param polylineSymbol	线symbol
 * @param polygonSymbol		面symbol
 * @param layerId			图层id，不传系统自动生成
 * @param clear				绘制前是否清楚历史	
 * @param Arcgis			ArcGis加载的modules	
 */
const draw = ({
	type = 'point',
	view = null,
	pointSymbol = symbol.point,
	polylineSymbol = symbol.polyline,
	polygonSymbol = symbol.polygon,
	layerId = null,
	clear = true,
	Arcgis: {
		SketchViewModel,
		GraphicsLayer
	}
}) => {
	return new Promise((resolve, reject) => {
		try {

			if (!view) return reject(new Error('请传入view对象'))
			if (!['point', 'polyline', 'polygon', 'multipoint', 'rectangle', 'circle'].includes(type))
				return reject(new Error('请传入正确的绘制类型'));

			let sketchLayer = getGraphicLayer(view, layerId, {
				GraphicsLayer
			});

			// clear && clearDrawGeometry({
			// 	view
			// });
			console.log(SketchViewModel, 'SketchViewModel');
			const sketchViewModel = new SketchViewModel({
				view,
				layer: sketchLayer,
				pointSymbol,
				polylineSymbol,
				polygonSymbol,
			});

			sketchViewModel.create(type);

			sketchViewModel.on('create', event => {
				if (event.state === 'complete') {
					// setMapViewState('unoccupied');
					resolve(event.graphic);
				}
			});

		} catch (e) {
			console.log(e);
		}
	})
}

// 获取图层graphic
const getGraphicLayer = (view, layerId = guid(), Arcgis) => {
	let graphicLayer = view.map.findLayerById(layerId) ||
		addGraphicLayer({
			view,
			layerId,
			Arcgis
		});
	console.log('graphicLayer: ', graphicLayer);
	return graphicLayer;
};

export default {
	draw
}